import axios from 'axios'
import store from '@/store'
import router from '@/router'
import to from 'await-to-js'
import { refreshTokenAPI } from '@/api/user'

const instance = axios.create({
  // http 服务器8000 websocket服务器8001
  baseURL: 'http://101.35.25.8:8000/v1_0/',
  timeout: 6000
})

// 请求拦截
instance.interceptors.request.use(config => {
  // 判断是否有token
  const token = store.state.user.token
  if (token) {
    config.headers.Authorization = 'Bearer ' + token
  }
  config.cancelToken = new axios.CancelToken((cancel) => {
    // cancel就是取消请求函数（虽然带了token一个单词但是和token没有任何关系）
    store.commit('user/pushCancelToken', {
      cancelToken: cancel
    })
  })
  return config
}, err => {
  return Promise.reject(err)
})
// 响应拦截
instance.interceptors.response.use(res => res.data, async err => {
  if (err.response && err.response.status === 401) {
    // 1.刷新Token
    // console.log(999999999)
    const [error, data] = await to(refreshTokenAPI(store.state.user.refresh_token))
    // console.log(data)
    if (error) {
      // token失效
      store.commit('user/setToken', '', '')
      router.push('/login?returnUrl=' + router.currentRoute.fullPath)
    } else {
      // 将拿到的token值赋值给store和localStorage
      // console.log('=========', data)
      // 再次请求之前的错误的请求
      await store.commit('user/setToken', data.data.data.token)

      // 再次请求之前的错误的请求
      return instance(err.config)
    }
  }
})

export default ({ url, method = 'get', headers, data, params }) => {
  const promise = instance({
    url,
    method,
    headers,
    data,
    params
  })
  return to(promise)
}
